Skip to content

修复游戏日志复制问题#1588

Open
icgnos wants to merge 1 commit into
mainfrom
fix/log
Open

修复游戏日志复制问题#1588
icgnos wants to merge 1 commit into
mainfrom
fix/log

Conversation

@icgnos

@icgnos icgnos commented May 4, 2026

Copy link
Copy Markdown
Collaborator

Checklist

  • Changes have been tested locally and work as expected.
  • All tests in workflows pass successfully.
  • Documentation has been updated if necessary.
  • Code formatting and commit messages align with the project's conventions.
  • Comments have been added for any complex logic or functionality if possible.

This PR is a ..

  • 🆕 New feature
  • 🐞 Bug fix
  • 🛠 Refactoring
  • ⚡️ Performance improvement
  • 🌐 Internationalization
  • 📄 Documentation improvement
  • 🎨 Code style optimization
  • ❓ Other (Please specify below)

Related Issues

Description

  • 修复了整行复制和高亮消失的问题,恢复了全选

Additional Context

  • Add any other relevant information or screenshots here.

Summary by Sourcery

Fix game log selection and copying behavior and restore full-select support in the standalone log viewer.

Bug Fixes:

  • Ensure copying game logs preserves exact character ranges across lines instead of truncating or misaligning the copied text.
  • Restore continuous text selection highlighting in the virtualized game log list so the highlight no longer disappears during interaction.

Enhancements:

  • Reintroduce a working Select All (Ctrl+A) behavior that selects the entire filtered game log content for copying.

@sourcery-ai

sourcery-ai Bot commented May 4, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Enhances game log text selection and copying by tracking character-level offsets, recalculating selection ranges on mouseup and select-all, and continuously restoring DOM selection highlights, while removing the previous index-only selection logic.

Sequence diagram for enhanced game log text selection and copy

sequenceDiagram
  actor User
  participant Browser
  participant GameLogPage
  participant SelectionState

  User->>Browser: mousedown on log line
  Browser->>GameLogPage: handleLogMouseDown(index, event)
  GameLogPage->>SelectionState: reset range and selecting
  GameLogPage->>Browser: window.getSelection().removeAllRanges()
  GameLogPage->>Browser: document.caretRangeFromPoint(event.clientX, event.clientY)
  Browser-->>GameLogPage: caretRange(startNode, startOffset)
  GameLogPage->>SelectionState: store start index, startOffset, end index, endOffset

  User->>Browser: mouseup after dragging selection
  Browser->>GameLogPage: handleMouseUp()
  GameLogPage->>SelectionState: selecting = false
  GameLogPage->>Browser: window.getSelection()
  Browser-->>GameLogPage: Selection with focusNode, focusOffset
  GameLogPage->>GameLogPage: findLogIndex(focusNode)
  GameLogPage->>SelectionState: update end index and endOffset

  User->>Browser: press Ctrl+A
  Browser->>GameLogPage: handleKeyDown(event)
  GameLogPage->>SelectionState: set range from first to last log
  GameLogPage->>SelectionState: startOffset = 0, endOffset = lastLog.length

  User->>Browser: press Ctrl+C
  Browser->>GameLogPage: handleCopy(event)
  GameLogPage->>SelectionState: read range(start, startOffset, end, endOffset)
  GameLogPage->>GameLogPage: normalize start and end
  GameLogPage->>GameLogPage: slice filteredLogs[start..end]
  GameLogPage->>GameLogPage: trim first and last line by offsets
  GameLogPage->>Browser: event.clipboardData.setData("text/plain", text)
  GameLogPage->>Browser: event.preventDefault()
Loading

File-Level Changes

Change Details Files
Track log selection with per-line character offsets instead of index-only ranges to support partial-line and multi-line copy.
  • Extended LogSelectionRange to include startOffset and endOffset to capture character positions within log lines.
  • Reset selection state and DOM selection on mousedown, then initialize range with the caret position using document.caretRangeFromPoint.
  • On key-based select-all, compute a full-range selection from the first to the last filtered log line, using line length as endOffset.
src/pages/standalone/game-log.tsx
Recompute the logical selection range on mouseup using the actual DOM focus node and map it back to the log index model.
  • Added findLogIndex helper to traverse up from a DOM node to its ancestor with data-log-index, returning the corresponding log index.
  • Updated global mouseup handler to stop selecting and update range.end and range.endOffset based on window.getSelection().focusNode and focusOffset.
src/pages/standalone/game-log.tsx
Rewrite copy handling to slice selected text based on stored offsets and handle single-line vs multi-line selections correctly.
  • Removed reliance on window.getSelection().toString and previous clamped start/end indices logic.
  • For single-line selections, slice the log line between startOffset and endOffset; for multi-line, slice the first and last line appropriately and join lines with newlines.
  • Skip copy handling when no logical range exists or resulting text is empty, and prevent default copy behavior when custom text is set.
src/pages/standalone/game-log.tsx
Continuously restore visual text selection highlighting in the log view, even when rows are virtualized or partially visible.
  • Introduced a requestAnimationFrame loop that inspects the stored range and window selection, skipping while a drag selection is in progress.
  • When both start and end rows are mounted, rebuild a DOM Range using the stored offsets and apply it to the selection; otherwise, scan visible rows to find the first and last within the range.
  • Handle cases where start/end rows are offscreen by adjusting offsets relative to visible rows, and clear DOM selection if no valid visible range exists, with errors silently ignored.
src/pages/standalone/game-log.tsx
Simplified mouse selection progression by removing per-row mouse enter handling and relying on mouseup-based range finalization.
  • Removed handleLogMouseEnter and its onMouseEnter binding from each log row container.
  • Stopped using clamp from utils/math since index clamping is no longer required in copy handling.
src/pages/standalone/game-log.tsx

Possibly linked issues

  • #unknown: Issue描述复制日志行丢失,PR修改选择与复制逻辑以保证连续行完整复制

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions github-actions Bot added the size/L Denotes a PR that changes 100-499 lines, ignoring generated files. label May 4, 2026

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • The requestAnimationFrame loop in the selection-restoration useEffect runs continuously even when there is no selection, which could be expensive; consider only scheduling it while a range exists or when selecting is true, and stopping when there is nothing to restore.
  • Using document.caretRangeFromPoint in handleLogMouseDown may cause compatibility issues because it is deprecated and not supported in all browsers; it would be safer to feature-detect and fall back to the standard document.caretPositionFromPoint/getSelection APIs where available.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `requestAnimationFrame` loop in the selection-restoration `useEffect` runs continuously even when there is no selection, which could be expensive; consider only scheduling it while a range exists or when `selecting` is true, and stopping when there is nothing to restore.
- Using `document.caretRangeFromPoint` in `handleLogMouseDown` may cause compatibility issues because it is deprecated and not supported in all browsers; it would be safer to feature-detect and fall back to the standard `document.caretPositionFromPoint`/`getSelection` APIs where available.

## Individual Comments

### Comment 1
<location path="src/pages/standalone/game-log.tsx" line_range="342-348" />
<code_context>
+  useEffect(() => {
+    let rafId: number;
+
+    const loop = () => {
+      rafId = requestAnimationFrame(() => {
+        const { range, selecting } = logSelectionStateRef.current;
+        const sel = window.getSelection();
+
+        if (!range || !sel || selecting) {
+          loop();
+          return;
+        }
</code_context>
<issue_to_address>
**suggestion (performance):** Avoid an always-on requestAnimationFrame loop when no selection exists

This effect creates a continuous `requestAnimationFrame` loop even when `range` is null, so the selection restoration logic runs every frame for the lifetime of the page. To avoid unnecessary work, only schedule new frames while there is an active selection (or `selecting` is true), and stop re-calling `loop()` once `range` is null and `selecting` is false.

Suggested implementation:

```typescript
  useEffect(() => {
    let rafId: number;

    const loop = () => {
      rafId = requestAnimationFrame(() => {
        const { range, selecting } = logSelectionStateRef.current;
        const sel = window.getSelection();
        const hasSelection = !!sel && sel.rangeCount > 0;

        // If there's no DOM selection and we're not in an active selection
        // gesture, stop scheduling new frames.
        if (!hasSelection && !selecting) {
          return;
        }

        // While there is an active selection gesture or we don't yet have a
        // restorable range/selection, keep polling.
        if (!range || !sel || selecting) {
          loop();
          return;
        }

        // Restore the selection range.
        sel.removeAllRanges();
        sel.addRange(range);

        // Continue polling while a selection still exists.
        loop();
      });
    };

    loop();

    return () => {
      if (rafId !== undefined) {
        cancelAnimationFrame(rafId);
      }
    };
  }, []);

```

If `logSelectionStateRef` or the selection-restoration behavior depends on additional state (e.g. props or other refs), you may need to:
1. Add those dependencies to the `useEffect` dependency array instead of `[]`.
2. Ensure that `logSelectionStateRef.current.selecting` is set to `false` when the user completes or cancels a selection; otherwise the loop will continue polling as if a selection gesture were still active.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +342 to +348
const loop = () => {
rafId = requestAnimationFrame(() => {
const { range, selecting } = logSelectionStateRef.current;
const sel = window.getSelection();

if (!range || !sel || selecting) {
loop();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (performance): Avoid an always-on requestAnimationFrame loop when no selection exists

This effect creates a continuous requestAnimationFrame loop even when range is null, so the selection restoration logic runs every frame for the lifetime of the page. To avoid unnecessary work, only schedule new frames while there is an active selection (or selecting is true), and stop re-calling loop() once range is null and selecting is false.

Suggested implementation:

  useEffect(() => {
    let rafId: number;

    const loop = () => {
      rafId = requestAnimationFrame(() => {
        const { range, selecting } = logSelectionStateRef.current;
        const sel = window.getSelection();
        const hasSelection = !!sel && sel.rangeCount > 0;

        // If there's no DOM selection and we're not in an active selection
        // gesture, stop scheduling new frames.
        if (!hasSelection && !selecting) {
          return;
        }

        // While there is an active selection gesture or we don't yet have a
        // restorable range/selection, keep polling.
        if (!range || !sel || selecting) {
          loop();
          return;
        }

        // Restore the selection range.
        sel.removeAllRanges();
        sel.addRange(range);

        // Continue polling while a selection still exists.
        loop();
      });
    };

    loop();

    return () => {
      if (rafId !== undefined) {
        cancelAnimationFrame(rafId);
      }
    };
  }, []);

If logSelectionStateRef or the selection-restoration behavior depends on additional state (e.g. props or other refs), you may need to:

  1. Add those dependencies to the useEffect dependency array instead of [].
  2. Ensure that logSelectionStateRef.current.selecting is set to false when the user completes or cancels a selection; otherwise the loop will continue polling as if a selection gesture were still active.

@UNIkeEN UNIkeEN left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

请先使用英文替换掉所有注释

@github-actions github-actions Bot added size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. and removed size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels May 5, 2026
@github-actions github-actions Bot added size/L Denotes a PR that changes 100-499 lines, ignoring generated files. and removed size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. labels May 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Denotes a PR that changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] 游戏日志窗口大段复制出现行丢失

2 participants